import os
import sys
import traceback

# 首先设置FFmpeg路径和解决导入问题
def setup_environment():
    try:
        # 设置FFmpeg路径
        if hasattr(sys, '_MEIPASS'):
            # 打包后的环境
            base_path = sys._MEIPASS
            ffmpeg_path = os.path.join(base_path, 'ffmpeg')
        else:
            # 开发环境
            base_path = os.path.dirname(os.path.abspath(__file__))
            ffmpeg_path = os.path.join(base_path, 'ffmpeg')
        
        # 添加到系统PATH
        if os.path.exists(ffmpeg_path) and ffmpeg_path not in os.environ['PATH']:
            os.environ['PATH'] = ffmpeg_path + os.pathsep + os.environ['PATH']
        
        # 设置pydub的ffmpeg路径
        ffmpeg_exe = os.path.join(ffmpeg_path, 'ffmpeg.exe')
        ffprobe_exe = os.path.join(ffmpeg_path, 'ffprobe.exe')
        
        if os.path.exists(ffmpeg_exe):
            os.environ['FFMPEG_PATH'] = ffmpeg_exe
        
    except Exception as e:
        print(f"环境设置错误: {e}")

# 立即执行环境设置
setup_environment()

# 现在导入其他模块
try:
    from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                                 QPushButton, QLabel, QLineEdit, QFileDialog, QProgressBar,
                                 QSpinBox, QGroupBox, QCheckBox, QMessageBox, QTextEdit)
    from PyQt5.QtCore import Qt, QThread, pyqtSignal
    import pydub
    from pydub import AudioSegment
    from pydub.generators import Sine
except ImportError as e:
    print(f"导入模块失败: {e}")
    print("请安装所需依赖: pip install PyQt5 pydub")
    input("按回车键退出...")
    sys.exit(1)

class AudioProcessorThread(QThread):
    """音频处理线程"""
    progress_signal = pyqtSignal(int, str)
    finished_signal = pyqtSignal(int, int)
    
    def __init__(self, input_dir, output_dir, silence_duration, formats):
        super().__init__()
        self.input_dir = input_dir
        self.output_dir = output_dir
        self.silence_duration = silence_duration
        self.formats = formats
        self.stop_flag = False
        
    def run(self):
        try:
            os.makedirs(self.output_dir, exist_ok=True)
            
            processed_count = 0
            error_count = 0
            total_files = 0
            
            # 先统计文件数量
            for filename in os.listdir(self.input_dir):
                file_ext = os.path.splitext(filename.lower())[1]
                if file_ext in self.formats:
                    total_files += 1
            
            if total_files == 0:
                self.progress_signal.emit(0, "没有找到符合条件的音频文件")
                self.finished_signal.emit(0, 0)
                return
            
            current_file = 0
            
            for filename in os.listdir(self.input_dir):
                if self.stop_flag:
                    break
                    
                file_ext = os.path.splitext(filename.lower())[1]
                
                if file_ext in self.formats:
                    current_file += 1
                    input_path = os.path.join(self.input_dir, filename)
                    output_path = os.path.join(self.output_dir, filename)
                    
                    self.progress_signal.emit(
                        int((current_file / total_files) * 100),
                        f"正在处理: {filename}"
                    )
                    
                    try:
                        # 读取音频文件
                        if input_path.lower().endswith('.wav'):
                            audio = AudioSegment.from_wav(input_path)
                        elif input_path.lower().endswith('.mp3'):
                            audio = AudioSegment.from_mp3(input_path)
                        else:
                            continue
                        
                        # 创建静音段
                        silence = AudioSegment.silent(
                            duration=self.silence_duration,
                            frame_rate=audio.frame_rate
                        )
                        
                        # 合并静音和原音频
                        combined = silence + audio
                        
                        # 导出文件，保持原音频参数
                        if output_path.lower().endswith('.wav'):
                            combined.export(
                                output_path,
                                format='wav'
                            )
                        elif output_path.lower().endswith('.mp3'):
                            combined.export(
                                output_path,
                                format='mp3',
                                bitrate="192k"  # 使用固定比特率避免问题
                            )
                        
                        processed_count += 1
                        
                    except Exception as e:
                        error_count += 1
                        error_msg = f"处理失败: {filename} - {str(e)}"
                        self.progress_signal.emit(
                            int((current_file / total_files) * 100),
                            error_msg
                        )
            
            self.finished_signal.emit(processed_count, error_count)
            
        except Exception as e:
            error_msg = f"处理过程中发生错误: {str(e)}"
            self.progress_signal.emit(0, error_msg)
            self.finished_signal.emit(0, 1)
    
    def stop(self):
        self.stop_flag = True

class AudioSilenceAdderGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.process_thread = None
        self.init_ui()
        
    def init_ui(self):
        self.setWindowTitle("音频静音添加工具 v1.0")
        self.setGeometry(100, 100, 600, 500)
        
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        
        # 输入目录选择
        input_group = QGroupBox("输入设置")
        input_layout = QVBoxLayout()
        
        input_path_layout = QHBoxLayout()
        self.input_path_edit = QLineEdit()
        self.input_path_edit.setPlaceholderText("请选择输入目录...")
        input_browse_btn = QPushButton("浏览")
        input_browse_btn.clicked.connect(self.browse_input)
        input_path_layout.addWidget(QLabel("输入目录:"))
        input_path_layout.addWidget(self.input_path_edit)
        input_path_layout.addWidget(input_browse_btn)
        input_layout.addLayout(input_path_layout)
        
        input_group.setLayout(input_layout)
        layout.addWidget(input_group)
        
        # 输出目录选择
        output_group = QGroupBox("输出设置")
        output_layout = QVBoxLayout()
        
        output_path_layout = QHBoxLayout()
        self.output_path_edit = QLineEdit()
        self.output_path_edit.setPlaceholderText("请选择输出目录...")
        output_browse_btn = QPushButton("浏览")
        output_browse_btn.clicked.connect(self.browse_output)
        output_path_layout.addWidget(QLabel("输出目录:"))
        output_path_layout.addWidget(self.output_path_edit)
        output_path_layout.addWidget(output_browse_btn)
        output_layout.addLayout(output_path_layout)
        
        output_group.setLayout(output_layout)
        layout.addWidget(output_group)
        
        # 参数设置
        params_group = QGroupBox("处理参数")
        params_layout = QVBoxLayout()
        
        # 静音时长
        duration_layout = QHBoxLayout()
        duration_layout.addWidget(QLabel("静音时长:"))
        self.duration_spin = QSpinBox()
        self.duration_spin.setRange(100, 60000)
        self.duration_spin.setValue(3000)
        self.duration_spin.setSuffix(" ms")
        duration_layout.addWidget(self.duration_spin)
        duration_layout.addStretch()
        params_layout.addLayout(duration_layout)
        
        # 文件格式选择
        format_layout = QHBoxLayout()
        format_layout.addWidget(QLabel("处理格式:"))
        self.wav_checkbox = QCheckBox("WAV")
        self.wav_checkbox.setChecked(True)
        self.mp3_checkbox = QCheckBox("MP3")
        self.mp3_checkbox.setChecked(True)
        format_layout.addWidget(self.wav_checkbox)
        format_layout.addWidget(self.mp3_checkbox)
        format_layout.addStretch()
        params_layout.addLayout(format_layout)
        
        params_group.setLayout(params_layout)
        layout.addWidget(params_group)
        
        # 进度显示
        progress_group = QGroupBox("处理进度")
        progress_layout = QVBoxLayout()
        
        self.progress_bar = QProgressBar()
        self.progress_bar.setValue(0)
        progress_layout.addWidget(self.progress_bar)
        
        self.status_label = QLabel("就绪")
        progress_layout.addWidget(self.status_label)
        
        self.log_text = QTextEdit()
        self.log_text.setMaximumHeight(150)
        self.log_text.setReadOnly(True)
        progress_layout.addWidget(self.log_text)
        
        progress_group.setLayout(progress_layout)
        layout.addWidget(progress_group)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        self.start_btn = QPushButton("开始处理")
        self.start_btn.clicked.connect(self.start_processing)
        self.stop_btn = QPushButton("停止")
        self.stop_btn.clicked.connect(self.stop_processing)
        self.stop_btn.setEnabled(False)
        
        button_layout.addWidget(self.start_btn)
        button_layout.addWidget(self.stop_btn)
        button_layout.addStretch()
        
        layout.addLayout(button_layout)
        
    def browse_input(self):
        directory = QFileDialog.getExistingDirectory(self, "选择输入目录")
        if directory:
            self.input_path_edit.setText(directory)
            
    def browse_output(self):
        directory = QFileDialog.getExistingDirectory(self, "选择输出目录")
        if directory:
            self.output_path_edit.setText(directory)
            
    def get_selected_formats(self):
        formats = []
        if self.wav_checkbox.isChecked():
            formats.append('.wav')
        if self.mp3_checkbox.isChecked():
            formats.append('.mp3')
        return formats
            
    def start_processing(self):
        input_dir = self.input_path_edit.text().strip()
        output_dir = self.output_path_edit.text().strip()
        silence_duration = self.duration_spin.value()
        formats = self.get_selected_formats()
        
        if not input_dir or not output_dir:
            QMessageBox.warning(self, "警告", "请选择输入和输出目录！")
            return
            
        if not formats:
            QMessageBox.warning(self, "警告", "请至少选择一种文件格式！")
            return
            
        if not os.path.exists(input_dir):
            QMessageBox.warning(self, "警告", "输入目录不存在！")
            return
            
        # 检查目录中是否有指定格式的文件
        has_files = False
        for filename in os.listdir(input_dir):
            if os.path.splitext(filename.lower())[1] in formats:
                has_files = True
                break
                
        if not has_files:
            QMessageBox.warning(self, "警告", "输入目录中没有找到指定格式的音频文件！")
            return
            
        self.start_btn.setEnabled(False)
        self.stop_btn.setEnabled(True)
        self.log_text.clear()
        
        self.process_thread = AudioProcessorThread(
            input_dir, output_dir, silence_duration, formats
        )
        self.process_thread.progress_signal.connect(self.update_progress)
        self.process_thread.finished_signal.connect(self.processing_finished)
        self.process_thread.start()
        
    def stop_processing(self):
        if self.process_thread and self.process_thread.isRunning():
            self.process_thread.stop()
            self.process_thread.wait()
            self.status_label.setText("处理已停止")
            self.log_text.append("处理已停止")
            
        self.start_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
        
    def update_progress(self, progress, message):
        self.progress_bar.setValue(progress)
        self.status_label.setText(message)
        self.log_text.append(message)
        
    def processing_finished(self, processed_count, error_count):
        self.progress_bar.setValue(100)
        self.status_label.setText(f"处理完成！成功: {processed_count}, 失败: {error_count}")
        self.log_text.append(f"处理完成！成功: {processed_count}, 失败: {error_count}")
        
        self.start_btn.setEnabled(True)
        self.stop_btn.setEnabled(False)
        
        if processed_count > 0:
            QMessageBox.information(self, "完成", 
                                  f"处理完成！\n成功: {processed_count} 个文件\n失败: {error_count} 个文件")
        
    def closeEvent(self, event):
        if self.process_thread and self.process_thread.isRunning():
            self.process_thread.stop()
            self.process_thread.wait()
        event.accept()

def main():
    app = QApplication(sys.argv)
    window = AudioSilenceAdderGUI()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()